package com.jie.strategy.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jie.config.OssConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 *
 * @author yezhiqiu
 * @date 2021/07/28
 */
@Service("ossUploadStrategyImpl")
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl {
    @Autowired
    private OssConfigProperties ossConfigProperties;

    @Override
    public Boolean exists(String filePath) {
        return getOssClient().doesObjectExist(ossConfigProperties.getBucketName(), filePath);
    }

    // 在类中定义一个成员变量 i
    private int i = 0;

    @Override
    public void upload(String path, String fileName, InputStream inputStream) {
        fileName = i + fileName;
        getOssClient().putObject(ossConfigProperties.getBucketName(), path + fileName, inputStream);
        System.out.println("上传成功");
    }

    @Override
    public String getFileAccessUrl(String filePath) {
        // 13547581873/刘天才3b8bccba1f9447419781026e4849c2fb.jpeg
        String[] array = filePath.split("\\.");
        filePath = array[0] + i + "." + array[1];
        i++; // 递增 i
        System.out.println("filePath: " + filePath);
        // 生成访问oss的url连接
        return ossConfigProperties.getUrl() + filePath;
    }


    /**
     * 获取ossClient
     *
     * @return {@link OSS} ossClient
     */
    private OSS getOssClient() {
        return new OSSClientBuilder().build(ossConfigProperties.getEndpoint(), ossConfigProperties.getAccessKeyId(), ossConfigProperties.getAccessKeySecret());
    }

}
